package com.pig.graduate.controller.material;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig.graduate.domain.material.MaterialPig;
import com.pig.graduate.domain.sys.SysUser;
import com.pig.graduate.mapper.sys.SysUserMapper;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.material.MaterialPigService;
import com.pig.graduate.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = {"物料管理"}, description = "物料管理")
@RestController
@RequestMapping("/material/pig")
public class MaterialPigController {

    @Autowired
    private MaterialPigService materialPigService;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 物料列表
     * @param materialPig
     * @return
     */
    @ApiOperation(value = "物料列表",notes = "物料列表")
    @PostMapping("/list")
    public MyResult supplierList(@RequestBody MaterialPig materialPig){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        SecurityContextHolder.getContext().setAuthentication(
        return materialPigService.materialList(materialPig);
    }

    /**
     * 物料新增修改
     * @param materialPig
     * @return
     */
    @ApiOperation(value = "新增修改",notes = "新增修改")
    @PostMapping("/addAndUpdate")
    public MyResult addAndUpdateSupplier(@RequestBody MaterialPig materialPig){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            String currentUserName = authentication.getName();
            SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username", currentUserName));
            materialPig.setOperatorsUser(sysUser.getId());
        }
        materialPigService.saveOrUpdate(materialPig);
        return MyResult.success();
    }

    /**
     * 物料删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除",notes = "删除")
    @PostMapping("/delete")
    public MyResult deleteSupplier(@RequestBody List<Long> ids){
        materialPigService.removeByIds(ids);
        return MyResult.success();
    }


}
